<template>
  <Modal
    :mask-closable="false"
    v-model="deviceVisible"
    width="1200"
    title="报工补录"
    class="modal-content-layout other"
  >
    <!-- {{ workInfo.cuttingPlanCode }} -->
    <Form
      ref="deviceForm"
      :model="formTop"
      label-position="top"
      :rules="validateDevice"
    >
      <div class="item">
        <Row :gutter="16">
          <Col :span="8">
            <FormItem label="工单号" prop="workCode">
              <Select
                v-model="formTop.workCode"
                filterable
                clearable
                placeholder="请输入工单号"
                :remote-method="handleRemote"
                :loading="searchLoading"
                @on-select="handleChange"
              >
                <Option
                  v-for="(item, i) in workOrderList"
                  :value="item.workCode"
                  :label="item.workCode"
                  :key="i"
                >
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="班次时间" prop="shiftTime">
              <DatePicker
                style="width: 100%"
                @on-change="shiftTimeChange"
                :value="formTop.shiftTime"
                type="date"
                placeholder="请选择班次时间"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="班次" prop="shiftId">
              <Select
                v-model="formTop.shiftId"
                placeholder="请选择班次"
                @on-select="shiftChange"
              >
                <Option
                  v-for="(item, i) in shiftList"
                  :value="item.id"
                  :label="item.shift"
                  :key="i"
                >
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="8">
            <FormItem label="提报方式" prop="reportingMethod">
              <Select
                :disabled="workInfo.cuttingPlanCode"
                v-model="formTop.reportingMethod"
                placeholder="请选择"
              >
                <Option label="按重量" value="按重量"></Option>
                <Option label="按数量" value="按数量"></Option>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="入库数量" prop="reportedQuantity">
              <InputNumber
                :disabled="workInfo.cuttingPlanCode"
                v-model="formTop.reportedQuantity"
                :precision="3"
              />
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="入库仓库" prop="wareHouse">
              <Input disabled v-model="formTop.wareHouse" />
            </FormItem>
            <!-- <FormItem label="入库仓库" prop="wareHouse">
              <Select
                @on-change="wareChange"
                v-model="formTop.warehouseId"
                placeholder="请选择"
              >
                <Option
                  v-for="(item, index) in rollList"
                  :key="index"
                  :value="item.rollNumber"
                  :label="item.rollNumber"
                ></Option>
              </Select>
            </FormItem> -->
          </Col>
        </Row>
        <Row :gutter="16" v-if="workInfo.cuttingPlanCode">
          <Col :span="8">
            <FormItem
              label="卷号"
              prop="rollNumber"
              :rules="{
                required: true,
                message: '请选择卷号',
                trigger: 'blur',
              }"
            >
              <Select
                v-model="formTop.rollNumber"
                @on-change="rollNumberChange"
                placeholder="请选择"
              >
                <Option
                  v-for="(item, index) in rollList"
                  :key="index"
                  :value="item.rollNumber"
                  :label="item.rollNumber"
                ></Option>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem
              label="卷重"
              prop="rollWeight"
              :rules="{
                required: true,
                message: '请输入卷重',
                trigger: 'blur',
                type: 'number',
              }"
            >
              <InputNumber
                :active-change="false"
                :precision="3"
                :parser="(val)=>util.numberFormatNoFixed(val,3)"
                @on-change="weightChange"
                v-model="formTop.rollWeight"
              />
            </FormItem>
          </Col>
          <Col :span="8">
            <!-- 开料 -->
            <FormItem label="操作人" prop="operators">
              <Select
                filterable
                :label-in-value="true"
                @on-change="userChange"
                :max-tag-count="1"
                multiple
                v-model="formTop.operators"
                placeholder="请选择"
              >
                <Option
                  v-for="(item, index) in userList"
                  :key="index"
                  :value="item.id"
                  :label="item.name + '--' + item.empno"
                ></Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="8">
            <FormItem label="备注" prop="remarks">
              <Input v-model="formTop.remarks" />
            </FormItem>
          </Col>
          <Col :span="8" v-if="!workInfo.cuttingPlanCode">
            <FormItem label="操作人" prop="operators">
              <Select
                filterable
                :label-in-value="true"
                @on-change="userChange"
                :max-tag-count="1"
                multiple
                v-model="formTop.operators"
                placeholder="请选择"
              >
                <Option
                  v-for="(item, index) in userList"
                  :key="index"
                  :value="item.id"
                  :label="item.name + '--' + item.empno"
                ></Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </div>
      <!-- {{ operators }} -->
      <div
        class="item mt16"
        v-if="operators.length != 0 && !workInfo.cuttingPlanCode"
      >
        <span v-for="(item, index) in operators" :key="index">
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="操作人">
                <Input :value="item.label" readonly />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="数量">
                <InputNumber :step="0.001" :parser="(val)=>util.numberFormatNoFixed(val,3)" :precision="3" :active-change="false" :min="0" v-model="item.num" />
              </FormItem>
            </Col>
          </Row>
        </span>
      </div>
    </Form>
    <div slot="footer">
      <Button type="default" @click="deviceVisible = false">{{
        $t("common.Cancle")
      }}</Button>
      <Button type="primary" :loading="loadingVisible" @click="submit">{{
        $t("maintenance.Confirmed")
      }}</Button>
    </div>
  </Modal>
</template>

<script>
import moment from "moment";
import util from "@/util/util";
export default {
  name: "addModalPro",
  data() {
    return {
      operators: [],
      deviceVisible: false,
      loadingVisible: false,
      searchLoading: false,
      formTop: {
        shiftTime: "",
      },
      shiftList: [],
      validateDevice: {
        workCode: [
          {
            required: true,
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        shiftTime: [
          {
            required: true,
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        shiftId: [
          {
            required: true,
            type: "number",
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        reportedQuantity: [
          {
            required: true,
            type: "number",
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        wareHouse: [
          {
            required: true,
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        reportingMethod: [
          {
            required: true,
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        feedingStatus: [
          {
            required: true,
            message: `${this.$t("common.selectInfo")}`,
            trigger: "change",
          },
        ],
        operators: [
          {
            required: true,
            message: `${this.$t("common.selectInfo")}`,
            trigger: "change",
            type: "array",
          },
        ],
      },
      workOrderList: [
        // { workCode: "1500000004001" },
        // { workCode: "1100003380001" },
      ],
      levels: [
        { label: "特急", value: "2" },
        { label: "紧急", value: "1" },
        { label: "一般", value: "0" },
      ],
      effects: [
        { label: "影响生产", value: "1" },
        { label: "不影响生产", value: "0" },
      ],
      userList: [],
      workInfo: {},
      addList: [],
      rollList: [],
    };
  },
  mounted() {
    this.getUserList();
  },
  watch: {
    operators: {
      handler() {
        if (this.workInfo.cuttingPlanCode) {
          return;
        }
        let sum = 0;
        for (let index = 0; index < this.operators.length; index++) {
          const element = this.operators[index];
          sum += Number(element.num || 0);
        }
        this.formTop.reportedQuantity = sum;
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    userChange(val) {
      this.operators = val;
      if (this.workInfo.cuttingPlanCode) {
        return;
      }
      for (let index = 0; index < this.operators.length; index++) {
        const value =
          this.operators[index].num == null ? 0 : this.operators[index].num;
        this.$set(this.operators[index], "num", value);
      }
    },
    rollNumberChange(value) {
      if (value) {
        const arg = this.rollList.find((item) => item.rollNumber === value);
        if (!arg) return;
        this.$set(this.formTop, "rollWeight", arg.rollWeight);
        console.log(999, value, arg);

        const reportedQuantity = Number(
          (arg.rollWeight / arg.rollMaterialWidth) * arg.materialWidth
        );
        this.$set(this.formTop, "reportedQuantity", reportedQuantity);
      }
    },
    // 卷重变化后
    weightChange(weightValue) {
      const value= Math.floor(weightValue*1000)/1000
      console.log(888, value);
      this.$set(this.formTop, "rollWeight",value);
      if (value == 0 || value == undefined || value == null) {
        this.$set(this.formTop, "reportedQuantity", 0);
      } else {
        const arg = this.rollList.find(
          (item) => item.rollNumber === this.formTop.rollNumber
        );
        //卷重÷卷料料宽*条料料宽
        if (!arg) return;
        const reportedQuantity = Number(
          (value / arg.rollMaterialWidth) * arg.materialWidth
        );
        
        this.$set(this.formTop, "reportedQuantity", reportedQuantity);
        console.log(reportedQuantity, "reportedQuantity");
      }
    },
    getUserList() {
      this.axios({
        url: "/dms/mobile/getUserNameList",
        method: "get",
        params: {
          pageSize: 10000,
          pageNum: 1,
        },
      }).then((res) => {
        this.userList = res.data.list;
      });
    },
    getWareHouse() {
      this.formTop.warehouseId = null;
      this.formTop.wareHouse = null;
      this.axios({
        url: "/dms/mobileEnd/getQualifiedWarehouse",
        method: "get",
        params: {
          deviceNo: this.workInfo.deviceCode,
        },
      }).then((res) => {
        this.formTop.warehouseId = res.data.id;
        this.formTop.wareHouse = res.data.backupName;
      });
    },
    getWorkInfo(val) {
      this.axios({
        url: "/dms/mobile/getRoductionReporting",
        method: "get",
        params: {
          workOrder: val,
        },
      }).then((res) => {
        this.workInfo = res.data;
        if (
          this.workInfo.cuttingPlanCode &&
          this.workInfo.cuttingPlanList &&
          this.workInfo.cuttingPlanList.length !== 0
        ) {
          this.rollList = this.workInfo.cuttingPlanList || [];
          this.formTop.rollNumber = this.rollList[0].rollNumber;
          this.formTop.reportingMethod = "按数量";
          this.formTop.rollWeight = this.rollList[0].rollWeight;
          this.$nextTick(() => {
            this.rollNumberChange(this.formTop.rollNumber);
          });
        } else {
          this.rollList = [];
        }
        this.getWareHouse();
      });
    },
    handleChange(val) {
      this.axios({
        url: "/dms/mobile/selectWorkByWorkCode",
        method: "get",
        params: {
          workCode: val.value,
        },
      }).then(() => {
        this.getWorkInfo(val.value);
      });
    },
    shiftTimeChange(val) {
      console.log(val);
      this.formTop.shiftTime = val;
      this.formTop.shiftId = null;
      this.getShiftList(val);
    },
    getShiftList(shiftTime) {
      this.shiftList = [];
      this.formTop.shiftId = null;
      this.formTop.shift = null;
      this.axios({
        url: "/dms/mobile/getShiftList",
        method: "get",
        params: {
          shiftDate: shiftTime ? moment(shiftTime).format("YYYY-MM-DD") : "",
          deviceNo: this.workInfo.deviceCode,
        },
      }).then((res) => {
        this.shiftList = res.data;
        this.formTop.shift = res.data[0].shift;
        this.formTop.shiftId = res.data[0].id;
        this.getAddList();
      });
    },
    shiftChange(obj) {
      this.formTop.shift = obj.label;
      this.formTop.shiftId = obj.value;
      this.getAddList();
    },
    getAddList() {
      if (!this.formTop.workCode && !this.formTop.shiftId) {
        this.$Message.warning("请先选择工单和班次");
        return;
      }
      this.axios({
        url: "/dms/mobileEnd/getMaterialAddList",
        method: "get",
        params: {
          pageSize: 50,
          pageNum: 1,
          workCode: this.formTop.workCode,
          shiftId: this.formTop.shiftId,
        },
      }).then((res) => {
        this.addList = res.data.records.map((item) => {
          return {
            ...item,
            weight: 1,
          };
        });
      });
    },

    show() {
      this.deviceVisible = true;
      this.formTop = {
        shiftTime: "", // moment().format('YYYY-MM-DD')
        shiftId: '',
        shift: null,
        wareHouse: null,
        warehouseId: null,
        rollNumber: "",
        reportingMethod: "按数量",
      };
      this.$refs.deviceForm.resetFields();
    },
    submit() {
      const that = this;
      this.$refs.deviceForm.validate((valid) => {
        if (valid) {
          const operatorNumber = this.operators.map((item) => item.value);
          let data = {
            ...that.formTop,
            operatorNumber,
            workCode: that.workInfo.workCode,
          };
          delete data.operators;
          if (!that.workInfo.cuttingPlanCode) {
            delete data.rollNumber;
            delete data.rollWeight;
            data.quantityS = that.operators.map((item) => item.num);

            let result = true;
            for (let i = 0; i < data.quantityS.length; i++) {
              if (data.quantityS[i] == 0) {
                result = false;
              }
            }
            if (!result) {
              that.$Message.warning("提报数量不能为空");
              return;
            }
          }else{
            if (data.operatorNumber.length !== 1) {
              that.$Message.warning("操作工只能选一人");
              return;
            }
          }
          this.loadingVisible = true;
          this.axios({
            url: "/dms/mobile/addReporting",
            method: "post",
            data,
          }).then((res) => {
            this.loadingVisible = false;
            if (res.code == 200) {
              this.$Message.success("操作成功");
              this.deviceVisible = false;
              this.$emit('refresh')
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    handleRemote(query) {
      if (query !== "") {
        this.searchLoading = true;
        let _query = query.split("-");
        if (Array.isArray(_query)) _query = _query[0];
        this.axios({
          method: "post",
          url: "/dms/productionWork/queryWorkList",
          data: {
            pageSize: 50,
            pageNum: 1,
            workCode: _query,
          },
        })
          .then((res) => {
            if (res.code === 200) {
              this.workOrderList = res.data.records;
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          })
          .finally(() => {
            this.searchLoading = false;
          });
      } else {
        this.numberList = [];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .ivu-modal-body {
  background: transparent !important;
  padding: 0 !important;
  box-shadow: none;
}

.item {
  background: #fff;
  border-radius: 8px;
  padding: 13px;
  box-shadow: 0px 4px 8px 0px rgba(0, 20, 45, 0.04);
}

.demo-upload-list {
  position: relative;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-left: 15px;

  img {
    width: 100%;
    height: 100%;
  }

  .delIcon {
    position: absolute;
    right: -10px;
    top: -10px;
    color: red;
    font-size: 20px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
  }
}
</style>
